<?php
namespace app\member\controller\api;
use app\ApiController;
use app\distribution\model\DistributionLog;
use app\mainadmin\model\SettingsModel;
use app\member\model\JiamenModel;
use app\member\model\NavMenuModel;
use app\member\model\TeamModel;
use app\member\model\UsersLevelApplyModel;
use app\member\model\UsersModel;

use app\shop\model\PrizeWinModel;
use app\supplyer\model\SupplyerModel;
use think\Db;

/*------------------------------------------------------ */
//-- 会员中心相关API
/*------------------------------------------------------ */

class Center extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->checkLogin();//验证登陆
        $this->Model = new UsersModel();
    }
    /*------------------------------------------------------ */
    //-- 获取会员中心首页所需数据
    /*------------------------------------------------------ */
    public function getCenterInfo()
    {
        //判断订单模块是否存在
        if(class_exists('app\shop\model\OrderModel')) {
            $OrderModel = new \app\shop\model\OrderModel();
            $data['orderStats'] = $OrderModel->userOrderStats($this->userInfo['user_id']);
            $where = [];
            $where[] = ['user_id','=',$this->userInfo['user_id']];
            $where[] = ['status','=',1];
            $collectNum = (new \app\shop\model\GoodsCollectModel)->where($where)->cache(true, 60)->count('collect_id');
            $data['collectNum'] = $collectNum;
            //$BonusModel = new \app\shop\model\BonusModel();
            //$bonus = $BonusModel->getListByUser();
            //$data['unusedNum'] = $bonus['unusedNum'];//未使用优惠券
        }
        $data['userInfo'] = $this->userInfo;
        $jcs = UsersLevelApplyModel::where("num", '>', 0)->select();
        $isShow =false;
        foreach ($jcs as $key => $jc) {
            if($jc['own_level']==$this->userInfo['role_id']){
                $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' =>$this->userInfo['user_id']])->field('user_id')->count();
                $additional_div = json_decode($this->userInfo['additional_div'], true);
                $additional_div = $additional_div[$jc['level_id']]['value'];
                if(intval($additional_div) || $jc['push_num']<=$pushCount){
                    $isShow=true;
                    break;
                }
            }
        }
        $menu =(new NavMenuModel)->getRows(3);

        //查询是否有分红
        $DistributionLogModel = new DistributionLog();
        $wheredis[] = ['user_id','=',$this->userInfo['user_id']];
        $distribution_jc_logObj = $DistributionLogModel->where($wheredis)->select()->toArray();

        $setModel = new SettingsModel();
        $material_auth = $setModel->where(['name' => 'material_auth'])->value('data');
        if($material_auth){
            $material_auth = explode(',',$material_auth);
        }else{
            $material_auth = [];
        }
        $supplierModel = new SupplyerModel();
        $supplier_audit = $supplierModel->where(['uid' =>  $this->userInfo['user_id']])->value('is_audit');

        if(empty($distribution_jc_logObj) && $this->userInfo['additional_setapply'] == 0){
            foreach ($menu as $key=> $val){
                if($val['title']=='奖池分红'){
                    if($isShow===false){
                        unset($menu[$key]);
                    }
                }
            }
        }
        foreach ($menu as $key=> $val){
            if(!$data['userInfo']['isRegion']){
                if ($val['title'] == '门店进货' || $val['title'] == '门店补贴') {
                    unset($menu[$key]);
                }
            }
            if(!$data['userInfo']['jxcshopgudong']){
                if ($val['title'] == '门店分红') {
                    unset($menu[$key]);
                }
            }
            if($data['userInfo']['role_id'] != 14){
                if ($val['title'] == '联创奖励') {
                    unset($menu[$key]);
                }
            }
            if ($val['title'] == '素材社区') {
                if(!in_array( $this->userInfo['role_id'],$material_auth)){
                    unset($menu[$key]);
                }
            }
            if ($val['title'] == '核销订单') {
                if(!$this->userInfo['isStaff']){
                    unset($menu[$key]);
                }
            }
            if ($val['title'] == '商户入驻') {
                if(!settings('sys_model_supplyer') && $supplier_audit == 1){
                    unset($menu[$key]);
                }
            }
            if ($val['title'] == '优惠券') {
                if(!settings('sys_model_shop_bonus')){
                    unset($menu[$key]);
                }
            }
        }

        $data['navMenu'] =$menu;
        $data['teamCount'] = (new TeamModel)->getTeamCountToCenter($this->userInfo['user_id']);




        //dump($data);
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 我的签到
    /*------------------------------------------------------ */
    /*------------------------------------------------------ */
    public function signIndex()
    {
        $signInfo = $this->Model->signInfo($this->userInfo['user_id']);
        $signInfo['use_integral'] = $this->Model->signIntegral();
        $signInfo['timeData'] = time();
        return $this->success($signInfo);
    }
    /*------------------------------------------------------ */
    //-- 我的签到记录
    /*------------------------------------------------------ */
    /*------------------------------------------------------ */
    public function signLog()
    {
        $yearMonth = input('yearMonth','','trim');
        if (empty($yearMonth)){
            $yearMonth = date('Y-m');
        }
        $signLog = $this->Model->signLog($this->userInfo['user_id'],$yearMonth);
        return $this->success($signLog);
    }
    /*------------------------------------------------------ */
    //-- 签到
    /*------------------------------------------------------ */
    public function signIng()
    {
        $res = $this->Model->signIng($this->userInfo['user_id']);
        if (is_array($res) == false) {
            return $this->error($res);
        }
        return $this->success('签到成功.','',$res);
    }



    /*------------------------------------------------------ */
    //-- 修改地址
    /*------------------------------------------------------ */
    public function editprize()
    {
        $uparr = $this->checkData();
        $where['id'] = $uparr['id'];
        $where['user_id'] = $this->userInfo['user_id'];

        $uparr['status'] = 1;
        $uparr['wlstatus'] = 1;
        $uparr['duihuantime'] = time();


        //验证数据是否出现变化
        //$dbarr = $this->Model->field(join(',',array_keys($uparr)))->where($where)->find()->toArray();
        //$this->checkUpData($dbarr,$uparr,true);

        $prizewinModel = new PrizeWinModel();
        //dump($where);
        $res = $prizewinModel->where($where)->update($uparr);
        if ($res < 1) return $this->error('修改失败，请重试.');

        return $this->success('200','','修改成功');
    }

    /*------------------------------------------------------ */
    //-- 验证修改/添加数据
    /*------------------------------------------------------ */
    private function checkData()
    {
        $data['username'] = input('username', '', 'trim');   //姓名
        $data['address'] = input('address', '', 'trim');
        $data['phone'] = input('phone', '', 'trim');
        $data['id'] = input('id', '', 'intval');
        if (empty($data['username'])) return $this->error('请输入收货人.');
        if (empty($data['address'])) return $this->error('请输入收货地址.');
        if (empty($data['phone'])) return $this->error('请输入手机号码.');
        if (checkMobile($data['phone']) == false) return $this->error('手机号码格式不正确.');

        return $data;
    }


    /*------------------------------------------------------ */
    //-- 验证修改/添加数据
    /*------------------------------------------------------ */
    public function getPrizewinData()
    {
        $id = input('id', '', 'intval');
        if(empty($id)){
            return $this->error("获取数据失败");
        }
        $prizewinModel = new PrizeWinModel();
        $res = $prizewinModel->where('id','=',$id)->find();

        //dump($res);

        return $this->success('ok','',$res);
    }


    /*------------------------------------------------------ */
    //-- 合作加盟申请
    /*------------------------------------------------------ */
    public function editjiamen()
    {
        $uparr = $this->checkjiamenData();
        //$where['id'] = $uparr['id'];
        //$where['user_id'] = $this->userInfo['user_id'];

        $uparr['status'] = 0;
        $uparr['is_delete'] = 0;
        $uparr['addtime'] = time();
        $uparr['user_id'] = $this->userInfo['user_id'];

        $JiamenModel = new JiamenModel();
        //dump($uparr);
        //$res = Db::table('shop_jiamen')->save($uparr);
        $res = $JiamenModel->save($uparr);
        if ($res < 1) return $this->error('申请失败，请重试.');

        return $this->success('200','','申请成功,等待平台审核');
    }

    /*------------------------------------------------------ */
    //-- 验证修改/添加数据
    /*------------------------------------------------------ */
    private function checkjiamenData()
    {
        $data['username'] = input('username', '', 'trim');   //姓名
        $data['address'] = input('address', '', 'trim');
        $data['phone'] = input('phone', '', 'trim');
        $data['level_id'] = input('level_id',0,'intval');
        //$data['hezuofs'] = input('hezuofs','','trim');
        //$data['id'] = input('id', '', 'intval');
        if (empty($data['username'])) return $this->error('请输入您的姓名.');
        if (empty($data['address'])) return $this->error('请输入详细地址.');
        if (empty($data['phone'])) return $this->error('请输入手机号码.');
        if (checkMobile($data['phone']) == false) return $this->error('手机号码格式不正确.');
        //if (empty($data['hezuofs'])) return $this->error('请选择所在地区.');
        if (empty($data['level_id'])) return $this->error('请选择代理级别.');

        $regionIds = input('regionIds', '', 'trim');

        if (empty($regionIds)) return $this->error('请选择所在地区1.');
        $regionIds = explode(',', $regionIds);
        $data['province'] = $regionIds[0];
        $data['city'] = $regionIds[1];
        $data['district'] = $regionIds[2];
        $data['street'] = $regionIds[3];
        if ($data['district'] < 1) return $this->error('请选择所在地区2.');

        //$regionInfo = (new \app\mainadmin\model\RegionModel)->info($data['district']);
        //$data['merger_name'] = $regionInfo['merger_name'];
        $data['hezuofs'] = $this->getAreasallname($regionIds[3]);

        return $data;
    }


    /*
     *
     * 获取地址全名
     */
    public function getAreasallname($id){

        if(empty($id)){
            return '无';
        }
        //$areasObj = new Areas();
        $areasRes = Db::table('t_areas')->where('id',$id)->find();
        $type = $areasRes['type'];
        if($type == 1){
            return $areasRes['name'];
        }else if($type == 2){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            return $pidRes['name'].','.$areasRes['name'];
        }else if($type == 3){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            return $pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }else if($type == 4){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            $pidpidpidRes = Db::table('t_areas')->where('id',$pidpidRes['pid'])->find();
            return $pidpidpidRes['name'].','.$pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }

    }




}
